package org.amn.concurrent;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;

/**
 * <p>
 * 描述:并发索引队列
 * </p>
 *
 * @see
 * @author yangjun1120@gmail.com
 *
 */
public class IndexConcurrentQueue<E> implements IindexQueue<E> {

    private static Logger logger = Logger.getLogger(IndexConcurrentQueue.class);

    private ConcurrentLinkedQueue<E> q;
    private int capacity;
    private AtomicInteger count = new AtomicInteger(0);

    public IndexConcurrentQueue(int aCapacity) {
        q = new ConcurrentLinkedQueue<E>();
        this.capacity = aCapacity;

    }

    @Override
    public void clear() {
        q.clear();
        count.set(0);
    }

    @Override
    public boolean isEmpty() {
        return q.isEmpty();
    }

    @Override
    public boolean offer(E e) {

        Assert.notNull(e, "object must be null!");

        if (count.get() >= capacity) {
            return false;
        }

        if (q.offer(e)) {
            count.incrementAndGet();
            return true;
        }

        return false;
    }

    @Override
    public E poll() {
        E e = q.poll();

        if (e != null) {
            count.decrementAndGet();
        }
        return e;
    }

    @Override
    public E peek() {
        return q.peek();
    }

    @Override
    public int size() {
        return count.get();
    }

    @Override
    public int capacity() {
        return this.capacity;
    }

}
